package com.ynunicom.midplatform.common.shiro.realm;


import com.ynunicom.midplatform.sys.permission.SysPermission;
import com.ynunicom.midplatform.sys.role.SysRole;
import com.ynunicom.midplatform.sys.user.SysUser;
import com.ynunicom.midplatform.sys.user.SysUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;

/**
 * 系统用户 Realm
 *
 * @author feiyu on 2018/5/2.
 */
public class SysUserRealm extends AuthorizingRealm {

    @Resource
    private SysUserService sysUserService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        SysUser sysUser = (SysUser) principals.getPrimaryPrincipal();
        for (SysRole role : sysUser.getRoleList()) {
            authorizationInfo.addRole(role.getCode());
            for (SysPermission p : role.getPermissions()) {
                authorizationInfo.addStringPermission(p.getPermission());
            }
        }
        return authorizationInfo;
    }

    /**
     * 主要是用来进行身份认证的，也就是说验证用户输入的账号和密码是否正确
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
            throws AuthenticationException {
        //获取用户的输入的账号.
        String loginName = (String) token.getPrincipal();
        //通过loginName从数据库中查找 User对象，如果找到，没找到.
        //实际项目中，这里可以根据实际情况做缓存，如果不做，Shiro自己也是有时间间隔机制，2分钟内不会重复执行该方法
        SysUser sysUser = sysUserService.findByLoginName(loginName);
        if (sysUser == null) {
            return null;
        }
        //账户冻结
        if (sysUser.getState() == 1) {
            throw new LockedAccountException();
        }
        return new SimpleAuthenticationInfo(
                //用户名
                sysUser,
                //密码
                sysUser.getPassword(),
                //salt=username+salt
                ByteSource.Util.bytes(sysUser.getSalt()),
                //realm name
                getName()
        );
    }

}
